package com.lawyer.service;

import javax.persistence.EntityManager;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import com.lawyer.dynamic.Criteria;
import com.lawyer.dynamic.Restrictions;
import com.lawyer.entity.Cases;
import com.lawyer.entity.Config;
import com.lawyer.entity.Lawyer;
import com.lawyer.model.CaseInfoReq;
import com.lawyer.model.Message;
import com.lawyer.repository.CaseInfoRepository;
import com.lawyer.repository.CasesRepository;
import com.lawyer.repository.ConfigRepository;
import com.lawyer.repository.LawyerRepository;

@Service
public class CaseInfoService {

	@Autowired
	private JdbcTemplate jdbcTemplate;

	Logger logger = LoggerFactory.getLogger(getClass());

	@Autowired
	private CaseInfoRepository caseInfoRepository;
	@Autowired
	private EntityManager entityManager;
	@Autowired
	private LawyerRepository lawyerRepository;
	@Autowired
	private ConfigRepository configRepository;

	@Autowired
	private CasesRepository casesRepository;

	public Message queryLawyerPage(CaseInfoReq caseInfoReq, Pageable pageable) {
		Sort sort = new Sort(Sort.Direction.ASC, "comprehensiveScore");
		// DESC=从高到低,ASC=从低到高
		if ("DESC".equals(caseInfoReq.getScore())) {
			sort = new Sort(Sort.Direction.DESC, "comprehensiveScore");
		}
		Pageable pageRequest = new PageRequest(pageable.getPageNumber(), pageable.getPageSize(), sort);

		Message msg = new Message();

		Criteria<Lawyer> criteria = new Criteria<Lawyer>();

		// 区域
		if (StringUtils.isNotEmpty(caseInfoReq.getLocation())) {
			criteria.add(Restrictions.or(Restrictions.eq("location", caseInfoReq.getLocation(), true)));
		}

		// 全部
		if (StringUtils.isNotEmpty(caseInfoReq.getCaseTypeId())) {
			Long caseId = Long.valueOf(caseInfoReq.getCaseTypeId());
			Cases cases = casesRepository.findOne(caseId);
			if (!"全部".equals(cases.getCaseType())) {
				criteria.add(Restrictions.or(Restrictions.like("caseTypeId", "%" + caseInfoReq.getCaseTypeId() + "%", true)));
			}
		}

		criteria.add(Restrictions.eq("certification", 2, true));

		Page<Lawyer> page = lawyerRepository.findAll(criteria, pageRequest);
		Config config = configRepository.findByName("ConsultingFee");// 律师咨询费
		for (Lawyer lawyer : page.getContent()) {
			lawyer.setConsultPrice(Double.valueOf(config.getValue()));
		}
		msg.setData(page);

		return msg;

	}

}